﻿using System;
using System.IO;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Aspose.Excel;
using System.Net.Mail;
using System.Net.Configuration;
using System.Web.Configuration;

namespace LenderClearingHouse
{
    public partial class RehabList : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["SourcePage"] = SourcePage.RehabList;
            listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);

            if (!IsPostBack)
            {
                DataAccess da = new DataAccess();
                DataTable tbl = da.ExecuteSQL("select * from Config");

                foreach (DataRow dr in tbl.Rows)
                {
                    if (dr["Key"].ToString() == "5daysVariable")
                    {
                        tb5daysVariable.Text = dr["Value"].ToString().Replace(",", ".");
                    }
                }

                SaveSortedPropertyIdsToSession(null);
            }

            try
            {
                grid.PageSize = int.Parse(Session[GridPageSizeSessionKey].ToString());
            }
            catch
            {
                grid.PageSize = 20;
            }
        }

        string GridPageSizeSessionKey { get { return "GridPageSize_" + this.GetType().Name; } }

        void SearchButton_Click(object sender, ImageClickEventArgs e)
        {
            grid.Rebind();
        }

        protected void SqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            if (!string.IsNullOrEmpty(Apn))
                e.Command.Parameters["@Apn"].Value = Apn;
            else
                e.Command.Parameters["@Apn"].Value = listFilter.Apn;
            e.Command.Parameters["@PropLocation"].Value = listFilter.Address;
            e.Command.Parameters["@Zip"].Value = listFilter.Zip;
        }

        protected void grid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            User u = Session["User"] as User;
            GridEditableItem editedItem = e.Item as GridEditableItem;
            RehabEditControl userControl = (RehabEditControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            DataAccess da = new DataAccess();

            da.ExecuteProcedure("updateRehab",
                new string[]
                {
                    "@PropertyId", "@RehabStatus", "@ActualCompDate", "@NotesStatus", "@NotesStatusDate", "@NotesStatusUser", "@PMId", "@RehabStartDate",
                    "@RehabEstimate", "@RehabMiscCosts", "@EstRehabCompDate"
                },
                new object[]
                {
                    (long)editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["PropertyId"],
                    (userControl.edRehabStatus.SelectedIndex==0)?"":userControl.edRehabStatus.Text, 
                    userControl.edActualCompDate.DbSelectedDate,
                    userControl.edNotesStatus.Text, DateTime.Now, u.FName + " " + u.LName, 
                    (userControl.edProjectManager.SelectedValue=="-1")?DBNull.Value:(userControl.edProjectManager.SelectedValue as object),
                    userControl.edRehabStartDate.DbSelectedDate,
                    userControl.edRehabEstimate.DbValue,
                    userControl.edMiscCosts.DbValue,
                    userControl.edEstRehabCompDate.DbSelectedDate
                });

            if (userControl.edProjectManager.SelectedValue != "-1")
            {
                int pmId = int.Parse(userControl.edProjectManager.SelectedValue);
                if (pmId != userControl.PMIdOld)
                {
                    DataTable tbl = da.ExecuteSQL("select * from UserAccounts where UserId = " + pmId);

                    try
                    {
                        SmtpClient client = new SmtpClient();
                        client.EnableSsl = true;

                        System.Configuration.Configuration config =
                          WebConfigurationManager.OpenWebConfiguration("~/");
                        SmtpSection smtpSection = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

                        MailMessage msg = new MailMessage();
                        msg.From = new MailAddress(smtpSection.Network.UserName);

                        msg.To.Add(tbl.Rows[0]["Email"].ToString());
                        msg.Subject = "Property Assignment Alert";
                        msg.IsBodyHtml = true;
                        msg.Body = File.ReadAllText(Server.MapPath("~/Template/PMPropertyAssignmentAlert.htm"));
                        msg.Body = msg.Body.Replace("%ProjectManager%",
                          tbl.Rows[0]["FName"].ToString() + " " + tbl.Rows[0]["LName"].ToString());
                        msg.Body = msg.Body.Replace("%PropertyAddress%", userControl.edPropertyLocation.Text);

                        client.Send(msg);

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "key",
                          "alert('Email to GC has been sent successfully');", true);
                    }
                    catch (Exception ex)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(),
                            "key", "alert('Error: " + ex.Message + "');", true);
                    }
                }
            }
        }

        protected void grid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem item = e.Item as GridPagerItem;
                RadComboBox combo = (RadComboBox)item.FindControl("PageSizeComboBox");

                RadComboBoxItem newItem = combo.Items.FindItemByValue("100");
                if (newItem == null)
                {
                    RadComboBoxItem citem = new RadComboBoxItem("100", "100");
                    citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                    combo.Items.Add(citem);
                }
                else
                {
                    newItem.Text = "100";
                }

                newItem = combo.Items.FindItemByValue("1000000");
                if (newItem == null)
                {
                    RadComboBoxItem citem = new RadComboBoxItem("ALL", "1000000");
                    citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                    combo.Items.Add(citem);

                    if (grid.PageSize == 1000000)
                    {
                        combo.SelectedValue = "1000000";
                    }
                }
                else
                {
                    newItem.Text = "ALL";
                }
            }
            else if (e.Item is GridDataItem)
            {
                GridDataItem itm = e.Item as GridDataItem;
                DataRowView drw = itm.DataItem as DataRowView;
                if (drw["RehabStartDate"] != DBNull.Value || drw["RehabStartDate"].ToString() != "")
                {
                    System.Drawing.Color c = System.Drawing.Color.FromArgb(189, 236, 182);
                    itm["RehabStartDate"].BackColor = c;
                }

                itm.BackColor = System.Drawing.Color.FromName(drw["BackColor"].ToString());

                string notesStatus = "";
                if (drw["NotesStatus"] != DBNull.Value)
                  notesStatus += drw["NotesStatus"].ToString();
                if (drw["NotesStatusDate"] != DBNull.Value)
                  notesStatus += " (" + Convert.ToDateTime(drw["NotesStatusDate"]).ToString("MM/dd/yyyy hh:mm tt") + " " + drw["NotesStatusUser"].ToString() + ")";
                itm["NotesStatus"].Text = notesStatus;
            }
        }

        protected void lnkExportToExcel_Click(object sender, EventArgs e)
        {
            Excel ex = Utilities.GetExcel();
            Worksheet ws = ex.Worksheets[0];

            DataAccess da = new DataAccess();
            DataTable dt = da.ExecuteSQL(string.Format("getRehab '{0}', '{1}', '{2}'",
              listFilter.Apn,
              listFilter.Address,
              listFilter.Zip));
            int startRow = 0;
            Utilities.GridToExcel(dt, grid, ws, true, ref startRow, 8);
            ex.Save("RehabDownload.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
            HttpContext.Current.Response.End();
        }

        protected void lnkRefreshGrid_Click(object sender, EventArgs e)
        {
            grid.Rebind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataAccess da = new DataAccess();
            da.ExecuteSQLNonQuery(
              string.Format("update Config set [Value] = '{0}' where [Key] = '5daysVariable'",
              tb5daysVariable.Text));
            grid.Rebind();
        }

        protected void grid_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
        {
            Session[GridPageSizeSessionKey] = e.NewPageSize.ToString();
        }

        protected void grid_SortCommand(object sender, GridSortCommandEventArgs e)
        {
            SaveSortedPropertyIdsToSession(e.SortExpression + " "
                + (e.NewSortOrder.ToString().StartsWith("Asc") ? "ASC" : "DESC"));
        }

        void SaveSortedPropertyIdsToSession(string sortExpression)
        {
            if (ForceEdit)
                return;

            DataTable tbl = (SqlDataSource.Select(DataSourceSelectArguments.Empty) as DataView).Table;
            List<int> ids = new List<int>();

            if (string.IsNullOrEmpty(sortExpression))
            {
                foreach (DataRow dr in tbl.Rows)
                {
                    ids.Add(Convert.ToInt32(dr["PropertyId"]));
                }
            }
            else
            {
                foreach (DataRow dr in tbl.Select("", sortExpression))
                {
                    ids.Add(Convert.ToInt32(dr["PropertyId"]));
                }
            }

            Session["AllPropertiesIds"] = ids.ToArray();
        }

        protected void grid_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (!Page.IsPostBack && e.Item is GridEditableItem && ForceEdit)
            {
                e.Item.Edit = true;
            }
        }

        protected string Apn
        {
            get
            {
                string result = "";
                if (Request.QueryString["apn"] != null)
                    result = Request.QueryString["apn"].ToString();

                return result;
            }
        }

        protected bool ForceEdit
        {
            get
            {
                return (Request.QueryString["edit"] != null);
            }
        }
    }
}